﻿using System;
using System.Web.UI;

using AjaxControlToolkit;

using IdeaNMR.Shared.Utils;
using IdeaNMR.Web.Core;
using System.Web;

namespace IdeaNMR.Web
{
    public partial class AllSetups : IdeaNMR_BasePage
    {
        private readonly string TabPositionCookie = "AllSetups_ASPX_TabPosition";

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Master.Title = "All Setup & Components";
            
            if (!Page.IsPostBack)
            {
                HttpCookie activeTabCookie = Request.Cookies[TabPositionCookie];
                if (activeTabCookie != null) tcComponents.ActiveTabIndex = int.Parse(activeTabCookie.Value);
            }
        }

        #region Event Handling
        protected void Table_Selected(object sender, IdeaNMR.Web.ItemSelectedCommandEventArgs e)
        {
            BaseObject n = e.SelectedItem;
            UriBuilder uri = new UriBuilder(ScrewTurnWikiFacade.MainUrl);

            if (!n.FirstVersionReference.IsLoaded) n.FirstVersionReference.Load();
            BaseObject f = n.FirstVersion;
            string cT = n.GetEntityType().ToString(); // Component Type for url

            // When NMRObject gets published it is insured, that its FirstVersion is public
            // If its first version is public already, then it stays as it is
            // If it is not public, means non of previous versions have been published,
            //      then for all these versions FirstVersion is changed to the NMRObject that is being published.
            // When NMRObject is published corresponding Wiki page is created.
            uri.Path += f.IsPrivate
                            ? string.Format("{0}_New.ashx", cT)
                            : string.Format("{0}_id_{1}.ashx", cT, f.Id);
            uri.AddQueryParameter("TargetID", n.Id.ToString());

            string resp = string.Format(@"parent.location='{0}';", uri.Uri.ToString());

            ToolkitScriptManager.RegisterClientScriptBlock(upMain, typeof(UpdatePanel), "Redirection", resp, true);
        }

        protected void tcComponents_TabChanged(object sender, EventArgs e)
        {
            Response.Cookies[TabPositionCookie].Value = ((AjaxControlToolkit.TabContainer)sender).ActiveTabIndex.ToString();
            Response.Cookies[TabPositionCookie].Expires = DateTime.Now.AddDays(30);
        }
        #endregion
    }
}